package com.canlihao.ui.view.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.canlihao.ui.R;
import com.canlihao.ui.base.BaseDialogFragment;
import com.canlihao.ui.utils.EventMessage;
import com.canlihao.ui.utils.MyLog;
import com.canlihao.ui.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by QYG_XXY on 0007 2017/12/7.
 */
@Route(path = "/app/case_update")
public class UpdateDialogFragment extends BaseDialogFragment {
    private static final String TAG = "UpdateDialogFragment";

    Unbinder unbinder;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.btnoff)
    Button btnoff;
    @BindView(R.id.btnon)
    Button btnon;
    @BindView(R.id.apk_name)
    TextView apkName;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.ll_progress)
    LinearLayout llProgress;
    String apkPath;
    String apkNameString;
    private boolean canceled = false;
    MyHandler myHandler;
    private String jzsj_str;
    private String dzblDocName;
    String dataAll = "", targetId = "";
    String stringVal = "";
    String getContent = "";
    String force = "";
    int numpro = 0;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_FRAME, R.style.dialog_full);
//        orderInfoId = getArguments().getString("orderInfoId");//6958
//        jzsj_str = getArguments().getString("jzsj");//2018-06-07
//        dzblDocName = getArguments().getString("dzblDocName");
        stringVal = getArguments().getString("url");
        force = getArguments().getString("force");
        getContent = getArguments().getString("content");
        //getContent = "1、"+StringUtils.getRandomChar(15)+";\n"+"2、"+StringUtils.getRandomChar(6)+";\n"+"3、"+StringUtils.getRandomChar(20)+";";
        //stringVal ="https://static.ss-clouddoctor.com/app/doctor_lastest.apk";
        MyLog.i(TAG, "->" + stringVal);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_update, container, false);
        unbinder = ButterKnife.bind(this, view);
        btnon.requestFocus();
        btnon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(btnon.getText().toString().equals("下载") || btnon.getText().toString().equals("重试")){
                    btnoff.setVisibility(View.GONE);
                    btnon.setText("下载中");
                    llProgress.setVisibility(View.VISIBLE);
                   thread.start();
                    //downloadFile();
                    Intent intent = new Intent(getActivity(), UpdateService.class);
                    intent.putExtra("url",stringVal);
                    intent.putExtra("banbenName","12323");
                    //getActivity().startService(intent);
                }else if(btnon.getText().toString().equals("安装")){
                    installApk();
                }
            }
        });
        if(force.equals("1")){
            btnoff.setVisibility(View.GONE);
        }else{
            btnoff.setVisibility(View.VISIBLE);
        }
        btnoff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDialog().dismiss();
                EventMessage myEventMessage1=EventMessage.getInstance("true",EventMessage.LaunchOff,"");
                EventBus.getDefault().post(myEventMessage1);
            }
        });
        tvContent.setText(getContent);
        update();
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener()
        {

            @Override
            public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent arg2) {
                // TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if(force.equals("1")){
                    }else{
                        getDialog().dismiss();
                        EventMessage myEventMessage1=EventMessage.getInstance("true",EventMessage.LaunchOff,"");
                        EventBus.getDefault().post(myEventMessage1);
                    }
                    return true;
                }
                return false;
            }
        });
        return view;
    }

    /**
     * 下载apk
     *
     * @author renzhiwen 创建时间 2014-8-16 下午3:32:34
     */
    class DownApkRunnable implements Runnable {

        @Override
        public void run() {

            downloadApk();
        }

    }
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            downloadApk();
        }
    });
        private int laterate = 0;
    private void downloadApk() {
        try {
            URL url = new URL(stringVal);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            int length = conn.getContentLength();
            int count = 0;
            File apkPathFile = new File(apkPath);
            if (!apkPathFile.exists()) {
                apkPathFile.mkdir();
            }
            File apkFile = new File(apkPath, apkNameString);
            File filesDir = getActivity().getFilesDir();
            InputStream in = conn.getInputStream();
            FileOutputStream os = new FileOutputStream(apkFile);
            byte[] buffer = new byte[1024];
            do {
                int numread = in.read(buffer);
                count += numread;
                int progress = (int) (((float) count / length) * 100);// 得到当前进度
                if (progress >= laterate + 1) {// 只有当前进度比上一次进度大于等于1，才可以更新进度
                    laterate = progress;
                    Message msg = new Message();
                    msg.what = 1;
                    msg.arg1 = progress;
                    //handler.sendMessage(msg);
                    myHandler.sendMessage(msg);
                }
                if (numread <= 0) {// 下载完毕
                    //handler.sendEmptyMessage(2);
                    myHandler.sendEmptyMessage(2);
                    canceled = true;
                    break;
                }
                os.write(buffer, 0, numread);
            } while (!canceled);// 如果没有被取消
            in.close();
            os.close();
        } catch (MalformedURLException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.showToast(getActivity(),"URL格式错误 ，请重试");
                    btnon.setText("重试");
                    btnoff.setVisibility(View.VISIBLE);
                }
            });

            e.printStackTrace();
        }catch (UnsupportedEncodingException e) {
            // 不支持你设置的编码
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.showToast(getActivity(),"不支持你设置的编码 ，请重试");
                }
            });
            e.printStackTrace();
        }catch (ProtocolException e) {
            // 请求方式不支持
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.showToast(getActivity(),"请求方式不支持 ，请重试");
                }
            });
            e.printStackTrace();
        }
        catch (IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.showToast(getActivity(),"输入输出通讯出错 ，请重试");
                    btnon.setText("重试");
                    btnoff.setVisibility(View.VISIBLE);
                }
            });

            e.toString();
            e.printStackTrace();
        }

    }
    /* 创建静态内部类
     */
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(getActivity()!=null){
                //执行业务逻辑
                switch (msg.what) {
                    case 1:// 更新进度
                        int progress = msg.arg1;
                        numpro = progress;
                        if (progress < 100) {
                            apkName.setText("Li");
                            tvProgress.setText(progress + "%");
                            progressbar.setProgress(progress);
                        } else {// 下载完成，停止服务
                            tvProgress.setText(progress + "%");
                            progressbar.setProgress(progress);
                            apkName.setText("Li");
                            if(force.equals("1")){
                                btnoff.setVisibility(View.GONE);
                            }else{
                                btnoff.setVisibility(View.VISIBLE);
                            }
                            btnon.setText("安装");
                        }
                        break;
                    case 2:// 安装apk
                        ToastUtil.showToast(getActivity(),"下载完成，请点击升级");
                        installApk();
                        break;

                    default:
                        break;
                }
            }
        }
    }
    /**
     * 安装apk
     */
    private void installApk() {
        File file = new File(apkPath,apkNameString);

        Intent intent = new Intent();

        intent.setAction(Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT >= 24)

        { // Android7.0及以上版本 Log.d("-->最新apk下载完毕","Android N及以上版本");

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.canlihao.ui.FileProvider", file);

//参数二:应用包名+".fileProvider"(和步骤二中的Manifest文件中的provider节点下的authorities对应)

            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

        } else {

// Android7.0以下版本 Log.d("-->最新apk下载完毕","Android N以下版本");

            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        this.startActivity(intent);

    }
    @Override
    public void onStart() {
        super.onStart();
        //得到dialog对应的window
        Window window = getDialog().getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();//得到LayoutParams
            //修改gravity
            params.gravity = Gravity.CENTER;
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
//            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//            window.getAttributes().windowAnimations = R.style.animate_dialog;
            window.setAttributes(params);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    public void update(){
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            apkPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
            apkNameString = "li_lastest.apk";
            //registerBroader();
            myHandler = new MyHandler();
            //new Thread(new DownApkRunnable()).start();
        } else {
            Toast.makeText(getActivity(), "SD卡不存在", Toast.LENGTH_SHORT)
                    .show();
        }
    }

}
